<?php
class FlowersUpgradeService {
    /**
     * @var FlowersUpgradeService
     */
    private static $instance;

    /**
     * Get the instance of FlowersUpgradeService.
     *
     * @return FlowersUpgradeService
     */
    public static function get() {
        if (!self::$instance) {
            self::$instance = new FlowersUpgradeService();
        }
        return self::$instance;
    }

    public function __construct() {
    }

    /**
     * 获取鲜花星级信息
     * @param $userId
     * @return array
     * @throws SzException
     */
    public function flowerStarInfo($userId) {
        $res = array(
            'code' => 0,
            'info' => array()
        );

        /**
         * @var $flowerStarList FlowerStarInfoVoList
         * @var $flowerStarInfo FlowerStarInfoVo
         */
        $flowerStarList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_STAR);
        if ($flowerStarList->getListCount() != 0){
            foreach ($flowerStarList->toArray() as $key=>$data){
                $firstData = explode(':',$data['first']);
                $secondData = explode(':',$data['second']);
                $thirdData = explode(':',$data['third']);
                $res['info'][$key][1]['state'] = $firstData[0];
                $res['info'][$key][1]['id'] = $firstData[1];
                $res['info'][$key][1]['func'] = $firstData[2];
                $res['info'][$key][1]['data'] = $firstData[3];
                $res['info'][$key][1]['pos'] = 1;
                $res['info'][$key][2]['state'] = $secondData[0];
                $res['info'][$key][2]['id'] = $secondData[1];
                $res['info'][$key][2]['func'] = $secondData[2];
                $res['info'][$key][2]['data'] = $secondData[3];
                $res['info'][$key][2]['pos'] = 2;
                $res['info'][$key][3]['state'] = $thirdData[0];
                $res['info'][$key][3]['id'] = $thirdData[1];
                $res['info'][$key][3]['func'] = $thirdData[2];
                $res['info'][$key][3]['data'] = $thirdData[3];
                $res['info'][$key][3]['pos'] = 3;
            }
        }

        return $res;
    }

    /**
     * 鲜花升星
     * @param $userId
     * @param $flower
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function flowerUpdateStar($userId,$flower,$pos,$reqTime) {
        $res = array(
            'code' => 0,
            'state' => false,
            'pos' => 0,
            'func' => 0,
            'data' => 0
        );

        //获取相关配置
        $needLevelConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarPremise', true)['value']);
        $needDiamondConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarGetPrice', true)['value']);
        $weightConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarAdditionWeight', true)['value']);
        $starConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR, null, true);
        $flowerConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SEED_CONDITION, $flower, true);
        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $flower, true);
        $refreshConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR_REFRESH, $pos, true);
        $refreshConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR_REFRESH, null, true);


        if (empty($needLevelConfig) || $needLevelConfig == null || $needLevelConfig == '' ||
            empty($needDiamondConfig) || $needDiamondConfig == null || $needDiamondConfig == '' ||
            empty($weightConfig) || $weightConfig == null || $weightConfig == '' ||
            empty($starConf) || $starConf == null || $starConf == '' ||
            empty($cropSetting) || $cropSetting == null || $cropSetting == '' ||
            empty($refreshConf) || $refreshConf == null || $refreshConf == '' ||
            empty($flowerConf) || $flowerConf == null || $flowerConf == ''
        ){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //获取玩家花朵数据
        /**
         * @var $flowerList PlantSeedVoList
         * @var $flowerInfo PlantSeedVo
         */
        $flowerList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_PLANT_SEED);
        $flowerInfo = $flowerList->getElement($flower, false);
        if (!$flowerInfo){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['DATA_NOT_EXIST'];//数据不存在
            return $res;
        }

        $flowerLevel = $flowerInfo->getLevel();
        if ($flowerLevel + 1 < $needLevelConfig[$pos - 1]){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_LEVEL_ERR'];//花朵等级不足
            return $res;
        }

        //获取玩家消耗的道具
        $itemArr = array();
        $i = 1;
        foreach ($flowerConf['itemId'][0] as $key=>$itemNum){
            if ($pos == $i){
                $itemArr[$key] = ceil($itemNum*($refreshConfs[$pos]['propPercent']/100));
                break;
            }
            $i++;
        }

        $num = 0;
        foreach ($cropSetting['coin'] as $key=>$itemNum1){
            if ($key == $refreshConf['flowerLevel']){
                $num = ceil($itemNum1*($refreshConf['consumePercent']/100));
                break;
            }
        }

        if ($refreshConf['currencyType'] == 1){
            //金币
            $itemArr[GameConst::ENTITY_ACTION_CONSUME_TOKEN] = $num;
        }
        if ($refreshConf['currencyType'] == 2){
            //钻石
            $itemArr[GameConst::ENTITY_ACTION_CONSUME_MONEY] = $num;
        }

        $input = '';
        foreach($itemArr as $item=>$value){
            GameService::get()->handleEntity($userId,$item, $value, true);
            $input .= $item.':'.$value.'|';
        }
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_FLOWER_UPDATE,$userId,0,$input,'starPosUnLock');//消耗资源上报

        $newData = array();
        $tempData = array();
        $state = 0;
        //获取玩家该花朵的升星数据
        /**
         * @var $flowerStarList FlowerStarInfoVoList
         * @var $flowerStarInfo FlowerStarInfoVo
         */
        $flowerStarList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_STAR);
        $flowerStarInfo = $flowerStarList->getElement($flower, false);
        if (!$flowerStarInfo){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_NOT_UNLOCK'];//改花升级没有解锁
            return $res;
        }
        else{
            if ($pos == 1){
                $state = explode(':',json_decode($flowerStarInfo->getFirst()))[0];
            }
            if ($pos == 2){
                $state = explode(':',json_decode($flowerStarInfo->getSecond()))[0];
            }
            if ($pos == 3){
                $state = explode(':',json_decode($flowerStarInfo->getThird()))[0];
            }

            if (!$state){
                $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_NOT_UNLOCK'];//改花升级没有解锁
                return $res;
            }

            $newData = $this->getRandomConfig($weightConfig,$starConf);
            $tempData = $pos.':1:'.$newData[2].':'.$newData[0].':'.$newData[1];
            $flowerStarInfo->setTemp($tempData);
            $flowerStarInfo->setUpdateTime($reqTime);
        }

        $flowerStarList->updateElement($flower, $flowerStarInfo);
        SzPersister::get()->setVoList($flowerStarList);

        $res['state'] = true;
        $res['pos'] = $pos;
        $res['func'] = $newData[0];
        $res['data'] = $newData[1];
        $res['id'] = $newData[2];
        return $res;
    }

    /**
     * 鲜花升星
     * @param $userId
     * @param $flower
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function flowerUpdateStarConfirm($userId,$flower,$pos,$reqTime) {
        $res = array(
            'code' => 0,
            'state' => false,
            'pos' => 0,
            'func' => 0,
            'data' => 0
        );

        //获取相关配置
        $needLevelConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarPremise', true)['value']);
        $needDiamondConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarGetPrice', true)['value']);
        $weightConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarAdditionWeight', true)['value']);
        $starConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR, null, true);
        $flowerConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_SEED_CONDITION, $flower, true);
        $cropSetting = SzConfig::get()->loadAppConfig(GameConst::CONFIG_PLANT_CROP, $flower, true);
        $refreshConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR_REFRESH, $pos, true);
        $refreshConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR_REFRESH, null, true);


        if (empty($needLevelConfig) || $needLevelConfig == null || $needLevelConfig == '' ||
            empty($needDiamondConfig) || $needDiamondConfig == null || $needDiamondConfig == '' ||
            empty($weightConfig) || $weightConfig == null || $weightConfig == '' ||
            empty($starConf) || $starConf == null || $starConf == '' ||
            empty($cropSetting) || $cropSetting == null || $cropSetting == '' ||
            empty($refreshConf) || $refreshConf == null || $refreshConf == '' ||
            empty($flowerConf) || $flowerConf == null || $flowerConf == ''
        ){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //获取玩家花朵数据
        /**
         * @var $flowerList PlantSeedVoList
         * @var $flowerInfo PlantSeedVo
         */
        $flowerList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_PLANT_SEED);
        $flowerInfo = $flowerList->getElement($flower, false);
        if (!$flowerInfo){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['DATA_NOT_EXIST'];//数据不存在
            return $res;
        }

        $flowerLevel = $flowerInfo->getLevel();
        if ($flowerLevel + 1 < $needLevelConfig[$pos - 1]){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_LEVEL_ERR'];//花朵等级不足
            return $res;
        }

        //获取玩家该花朵的升星数据
        /**
         * @var $flowerStarList FlowerStarInfoVoList
         * @var $flowerStarInfo FlowerStarInfoVo
         */
        $flowerStarList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_STAR);
        $flowerStarInfo = $flowerStarList->getElement($flower, false);
        if (!$flowerStarInfo){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_NOT_UNLOCK'];//改花升级没有解锁
            return $res;
        }
        else{
            if ($pos == 1){
                $state = explode(':',json_decode($flowerStarInfo->getFirst()))[0];
            }
            if ($pos == 2){
                $state = explode(':',json_decode($flowerStarInfo->getSecond()))[0];
            }
            if ($pos == 3){
                $state = explode(':',json_decode($flowerStarInfo->getThird()))[0];
            }

            if (!$state){
                $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_NOT_UNLOCK'];//改花升级没有解锁
                return $res;
            }

            $tempData = explode(':',json_decode($flowerStarInfo->getTemp()));
            if ($tempData[0] != $pos){
                $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_CONFIRM_ERR'];//确认数据有误
                return $res;
            }

            if ($pos == 1){
                $flowerStarInfo->setFirst('1:'.$tempData[2].':'.$tempData[3].':'.$tempData[4]);
            }
            if ($pos == 2){
                $flowerStarInfo->setSecond('1:'.$tempData[2].':'.$tempData[3].':'.$tempData[4]);
            }
            if ($pos == 3){
                $flowerStarInfo->setThird('1:'.$tempData[2].':'.$tempData[3].':'.$tempData[4]);
            }
            $flowerStarInfo->setUpdateTime($reqTime);
        }

        $flowerStarList->updateElement($flower, $flowerStarInfo);
        SzPersister::get()->setVoList($flowerStarList);

        $res['state'] = true;
        $res['pos'] = $pos;
        $res['func'] = $tempData[3];
        $res['data'] = $tempData[4];
        $res['id'] = $tempData[2];
        return $res;
    }

    /**
     * 鲜花星级位置解锁
     * @param $userId
     * @param $flower
     * @param $pos
     * @param $reqTime
     * @return array
     * @throws SzException
     */
    public function starPosUnLock($userId,$flower,$pos,$reqTime) {
        $res = array(
            'code' => 0,
            'state' => false,
            'pos' => 0,
            'func' => 0,
            'data' => 0
        );

        //获取相关配置
        $needLevelConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarPremise', true)['value']);
        $needDiamondConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarGetPrice', true)['value']);
        $weightConfig = json_decode(SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'flowerStarAdditionWeight', true)['value']);
        $starConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR, null, true);

        if (empty($needLevelConfig) || $needLevelConfig == null || $needLevelConfig == '' ||
            empty($needDiamondConfig) || $needDiamondConfig == null || $needDiamondConfig == '' ||
            empty($weightConfig) || $weightConfig == null || $weightConfig == '' ||
            empty($starConf) || $starConf == null || $starConf == ''
        ){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['CONFIG_NOT_EXIST'];//配置不存在
            return $res;
        }

        //获取玩家花朵数据
       /**
        * @var $flowerList PlantSeedVoList
        * @var $flowerInfo PlantSeedVo
        */
        $flowerList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_PLANT_SEED);
        $flowerInfo = $flowerList->getElement($flower, false);
        if (!$flowerInfo){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['DATA_NOT_EXIST'];//数据不存在
            return $res;
        }

        $flowerLevel = $flowerInfo->getLevel();
        if ($flowerLevel + 1 < $needLevelConfig[$pos - 1]){
            $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_LEVEL_ERR'];//花朵等级不足
            return $res;
        }

        //获取玩家消耗的道具
        GameService::get()->handleEntity($userId,GameConst::ENTITY_ACTION_CONSUME_MONEY, $needDiamondConfig[$pos - 1], true);
        CommonFunctionService::get()->reportResourceUseDetails(GameConst::FUNC_FLOWER_UPDATE,$userId,0,GameConst::ENTITY_ACTION_CONSUME_MONEY.':'.$needDiamondConfig[$pos - 1].'|','starPosUnLock');//消耗资源上报

        //获取玩家该花朵的升星数据
        $unlockData = array();
        $state = 0;
        /**
         * @var $flowerStarList FlowerStarInfoVoList
         * @var $flowerStarInfo FlowerStarInfoVo
         */
        $tempData = '0:0:0:0:0';
        $flowerStarList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_STAR);
        $flowerStarInfo = $flowerStarList->getElement($flower, false);
        if ($flowerStarInfo){
            if ($pos == 1){
                $state = explode(':',json_decode($flowerStarInfo->getFirst()))[0];
            }
            if ($pos == 2){
                $state = explode(':',json_decode($flowerStarInfo->getSecond()))[0];
            }
            if ($pos == 3){
                $state = explode(':',json_decode($flowerStarInfo->getThird()))[0];
            }
            if ($state){
                $res['code'] = GameConst::EXCEPTION_CODE_ARRAY['FLOWER_STAR_UNLOCK'];//该星级已经解锁
                return $res;
            }

            $unlockData = $this->getRandomConfig($weightConfig,$starConf);
            if ($pos == 1){
                $flowerStarInfo->setFirst('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]);
            }
            if ($pos == 2){
                $flowerStarInfo->setSecond('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]);
            }
            if ($pos == 3){
                $flowerStarInfo->setThird('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]);
            }
            $flowerStarInfo->setUpdateTime($reqTime);
        }
        else{
            $initData = '0:0:0:0';
            $unlockData = $this->getRandomConfig($weightConfig,$starConf);
            $flowerStarInfo = new FlowerStarInfoVo(
                $userId,
                $flower,
                json_encode($tempData),
                $pos == 1 ? json_encode('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]) : json_encode($initData),
                $pos == 2 ? json_encode('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]) : json_encode($initData),
                $pos == 3 ? json_encode('1:'.$unlockData[2].':'.$unlockData[0].':'.$unlockData[1]) : json_encode($initData),
                $reqTime,
                $reqTime,
                true
            );
        }

        if ($flowerStarInfo->isInsert() && !SzUtility::checkArrayKey($flower, $flowerStarList->getList())) {
            $flowerStarList->addElement($flowerStarInfo);
            $flowerStarList->setElement($flower, $flowerStarInfo);
        } else {
            $flowerStarList->updateElement($flower, $flowerStarInfo);
        }

        SzPersister::get()->setVoList($flowerStarList);

        $res['state'] = true;
        $res['pos'] = $pos;
        $res['func'] = $unlockData[0];
        $res['data'] = $unlockData[1];
        $res['id'] = $unlockData[2];
        return $res;
    }

    /*
     * 获取随机属性
     */
    public function getRandomConfig($weightConfig,$starConf) {
        $result = array();
        $tempWeigh = array();
        //获取加成类型
        foreach ($weightConfig as $key=>$weight){
            $tempWeigh[] = array('type' => $key + 1, 'weight' => $weight);
        }

        $useConf = array();
        $tempType = array();
        $type = CommonFunctionService::get()->weightRandom($tempWeigh)['type'];
        $result[] = $type;
        foreach ($starConf as $key=>$conf){
            if ($type == $conf['additionKind']){
                $useConf[] = $conf;
                $tempType[] = array('type' => $conf['ID'], 'weight' => $conf['Weight']);
            }
        }

        //进行数值随机
        $smallType = CommonFunctionService::get()->weightRandom($tempType)['type'];
        //进行数据整合
        if ($starConf[$smallType]['numKind'] == 1){
            $result[] = $starConf[$smallType]['additionPercent'];
        }
        if ($starConf[$smallType]['numKind'] == 2){
            $result[] = $starConf[$smallType]['additionNum'];
        }
        $result[] = $smallType;

        return $result;
    }

    /**
     * 获取鲜花加成
     * @param $userId
     * @param $flower
     * @param $type
     * @return array
     */
    public function getFlowerBuff($userId,$flower,$type) {
        $res = array();
        /**
         * @var $flowerStarList FlowerStarInfoVoList
         * @var $flowerStarInfo FlowerStarInfoVo
         */
        $flowerStarList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_FLOWER_STAR);
        $flowerStarInfo = $flowerStarList->getElement($flower, false);
        if (!$flowerStarInfo){
            return $res;
        }
        else{
            $temp = 0;
            //获取buff配置
            $starConf = SzConfig::get()->loadAppConfig(GameConst::CONFIG_FLOWER_STAR, null, true);
            foreach ($starConf as $key=>$conf){
                if ($conf['additionKind'] == $type){
                    $res[] = $conf['numKind'];
                    break;
                }
            }
            if (count($res) < 1){
                return array();
            }
            $firstBuff = explode(':',json_decode($flowerStarInfo->getFirst()));
            if ($firstBuff[2] == $type){
                $temp +=  $firstBuff[3];
            }

            $secondBuff = explode(':',json_decode($flowerStarInfo->getSecond()));
            if ($secondBuff[2] == $type){
                $temp +=  $secondBuff[3];
            }

            $thirdBuff = explode(':',json_decode($flowerStarInfo->getThird()));
            if ($thirdBuff[2] == $type){
                $temp +=  $thirdBuff[3];
            }

            $res[] = $temp;
        }

        return $res;
    }



}